from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from models import *
from repositories.news_data import NewsDataRepository
from utils.util import api_stats_counter, get_stats

logger.add("data_server.log", format="{time} {level} {message}", backtrace=True, diagnose=True)

app = FastAPI(debug=True)
# 添加中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源跨域请求
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP请求头
)


@app.post("/api/get_information_list", response_model=Union[SuccessResponseModel, ErrorResponseModel],
          response_model_exclude_unset=True)
@api_stats_counter
def get_information_list(item: ItemModel):
    logger.info(f"/api/get_information_list: {item}")
    try:
        # 资讯数据查询
        results = NewsDataRepository().select(item, "information_data")
        return SuccessResponseModel(Status=200, result=results)
    except Exception as e:
        logger.error(f"get_news_list:{item}-->{e}")
        return ErrorResponseModel(Status=500, result="")


@app.get("/api/get_project_list", response_model=Union[SuccessResponseModel, ErrorResponseModel],
         response_model_exclude_unset=True)
@api_stats_counter
def get_project_list():
    try:
        # 资讯数据查询
        results = NewsDataRepository().project_select("information_data")
        return SuccessResponseModel(Status=200, result=results)
    except Exception as e:
        logger.error(f"get_project_list:-->{e}")
        return ErrorResponseModel(Status=500, result="")


@app.get("/api/get_detail", response_model=Union[SuccessResponseModel, ErrorResponseModel],
         response_model_exclude_unset=True)
@api_stats_counter
def get_detail(news_id: int):
    logger.info(f"/api/get_detail: {news_id}")
    try:
        # 资讯数据查询
        results = NewsDataRepository().detail_select("information_data", data_id=news_id)
        return SuccessResponseModel(Status=200, result=results)
    except Exception as e:
        logger.error(f"get_detail:{news_id}-->{e}")
        return ErrorResponseModel(Status=500, result="")


@app.get("/api/get_all_endpoints_state")
def get_all_endpoints_state():
    return get_stats()


@app.post("/api/upload_file", response_model=Union[SuccessResponseModel, ErrorResponseModel],
          response_model_exclude_unset=True)
@api_stats_counter
async def upload_file(file: UploadFile = File(...)):
    # 写到本地
    with open(file.filename, "wb") as f:
        f.write(file.file.read())
    # todo 写到oss
    return SuccessResponseModel(Status=200, result={"filename": file.filename})


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=81)
